<?php
namespace Admin\Controller;
use Admin\Controller\BaseController;

class MajorController extends BaseController {

	public function index() {
		$this->assign('majors', D('Major')->relation('academy')->select());
		$this->assign('academies', M('Academy')->select());
		$this->display();
	}

	public function addPost() {
		if(!IS_POST) {
			$this->redirect('Major/index');
		}
		$major = D('Major');
		if(!$major->create()) {
			$this->error($major->getError());
		}
		if(!$major->checkUnique($major->data())) {
			$this->error('专业已存在');
		}
		if(!$major->add()) {
			$this->error('数据写入失败！');
		}
		$this->success('添加成功！', U('Major/index'), 0);
	}

	public function deletePost() {
		if(!IS_POST) {
			$this->redirect('Major/index');
		}
		$id = (int)I('post.id');
		$major = D('Major');
		if($major->hasChildObj($id)) {
			$this->error($major->getError());
		}
		unset($major);
		if(M('Major')->where(array('id' => $id))->delete()) {
			$this->success('删除成功！', U('Major/index'), 0);
		} else {
			$this->error('删除失败！');
		}	
	}

	public function modifyPost() {
		if(!IS_POST) {
			$this->redirect('Major/index');
		}
		$major = D('Major');
		if(!$major->create()) {
			$this->error($major->getError());
		}
		if(!$major->checkUnique($major->data())) {
			$this->error('专业已存在');
		}
		$result = $major->save();
		if($result === false) {
			$this->error('数据更新失败！');
		}
		$this->success('修改成功！', U('Major/index'), 0);		
	}

	public function detail() {
		if(IS_POST) {
			$id = (int)I('post.id');
			$ret = array();
			$ret['academies'] = M('Academy')->select();
			$ret['major'] = D('Major')->where(array('id' => $id))->relation('academy')->find();
			$this->ajaxReturn($ret);
		}
		$this->redirect('Major/index');
	}

}
